package de.gdgkarlsruhe.programminfo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import android.util.Log;

public class ProgramminfoRequest {

	private static final String TAG = "ProgramminfoRequest";
	private static final String track1Url = "http://www.gdg-karlsruhe.de/devfest/2013/programm/track1.json";
	private static final String track2Url = "http://www.gdg-karlsruhe.de/devfest/2013/programm/track2.json";
	private static final String track3Url = "http://www.gdg-karlsruhe.de/devfest/2013/programm/track3.json";

	private int mTrackNo = 1;
	
	public ProgramminfoRequest(int trackNo) {
		super();
		mTrackNo = trackNo;
	}

	public List<Track> loadTrackData() {
		String trackUrl = track1Url;
		switch (mTrackNo) {
		case 1:
			trackUrl = track1Url;
			break;
		case 2:
			trackUrl = track2Url;
			break;
		case 3:
			trackUrl = track3Url;
			break;
		}
		Log.d(TAG, "Url: " + trackUrl);
		return doGet(trackUrl);
	}
	
	private List<Track> doGet(String trackUrl) {
		List<Track> data = new ArrayList<Track>();
		try {
			URL url = new URL(trackUrl);
			URLConnection connection = url.openConnection();
			HttpURLConnection httpConnection = (HttpURLConnection) connection;
			
			int responseCode = httpConnection.getResponseCode();
			if (responseCode == HttpURLConnection.HTTP_OK) {
				InputStream in = httpConnection.getInputStream();
				data.addAll(processStream(in));
			}
		}
		catch (MalformedURLException e) {
			Log.e(TAG, "Malformed Url Exception.", e);
		}
		catch (IOException e) {
			Log.e(TAG, "IO Exception.", e);
		}
		catch (JSONException e) {
			Log.e(TAG, "JSON Exception.", e);
		}
		return data;
	}
	
	private List<Track> processStream(InputStream in) throws IOException, JSONException {
		List<Track> data = new ArrayList<Track>();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		String content = "";
		StringBuilder response = new StringBuilder();
		while ((content = reader.readLine()) != null) {
			response.append(content);
		}
		Log.i(TAG, "Response wird geparst: " + response.toString());
		JSONArray jsonArray = new JSONArray(response.toString());
		for (int i = 0; i < jsonArray.length(); i++) {
			Track track = Track.fromJSONObject(jsonArray.getJSONObject(i));
			if (null != track) {
				data.add(track);
			}
		}
		return data;
	}
	
}
